package client

import (
	"chatting/model"
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/widget"
)

//BuildLogin 不仅要登录，还要负责Build MainWindow和make ChatList
func (la *LocalApp) BuildLogin() fyne.Window {
	window := la.app.NewWindow("登录")

	usernameE := widget.NewEntry()
	passwordE := widget.NewEntry()
	passwordE.Password = true

	form := widget.NewForm(
		widget.NewFormItem("用户名", usernameE),
		widget.NewFormItem("密码", passwordE),
	)

	form.SubmitText = "登录"
	form.OnSubmit = func() {
		message := model.NewLoginMessage(&model.User{
			Username: usernameE.Text,
			Password: passwordE.Text,
		})

		la.client.sendChan <- message
		resMsg := <-la.client.receiveChan

		switch resMsg.Typeis() {
		case model.PlainRes: //登录失败
			dialog.ShowInformation("登录错误", resMsg.(*model.ResPlainMessage).Data.(string), window)
			return
		case model.UserInfoRes:
			localUser.User = resMsg.(*model.ResUserInfoMessage).UserInfo
			fmt.Println(localUser.User)
			la.MainWindow = la.BuildMainWindow()
			la.chatList = make(map[string]binding.BytesList)
			la.chatWindow = make(map[string]fyne.Window)
			for _, friend := range localUser.Friends {
				la.chatList[friend.Username] = binding.NewBytesList()
			}
			go la.GhatListen()
			la.MainWindow.Show()
			window.Close()
		}
	}
	window.SetContent(form)
	return window
}
